from PIL import Image
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget , QFileDialog , QLabel , QVBoxLayout ,\
    QHBoxLayout, QPushButton , QTextEdit
from PyQt5.QtGui import QPixmap , QPainter, QPen , QColor , QPaintEvent

class ImageWidget(QWidget):
    def __init__(self,parent = None):
        super().__init__()
        self.fname = ''
        self.ftype = ''
        self.OCRText = ''
        self.vertex = (0,0,0,0)
        self.__uiInit()

    def __uiInit(self) -> None:
        self.Layout = QVBoxLayout()
        self.subLayout0 = QHBoxLayout()
        self.imageWindow = QLabel()
        self.imageMessage = QLabel()
        self.userTextInput = QTextEdit()
        self.confirmButton = QPushButton()
        self.reSelectButton = QPushButton()

        self.confirmButton.setText('确认')
        self.reSelectButton.setText('重新选择图片')
        self.userTextInput.setPlaceholderText('请输入对图片的描述')
        self.subLayout0.addWidget(self.reSelectButton)
        self.subLayout0.addWidget(self.confirmButton)
        self.Layout.addWidget(self.imageWindow)
        self.Layout.addWidget(self.imageMessage)
        self.Layout.addWidget(self.userTextInput)
        self.Layout.addLayout(self.subLayout0)
        self.setLayout(self.Layout)

    def openImage(self) -> None:
        #self指向自身，"Open File"为文件名，"./"为当前路径，最后为文件类型筛选器
        self.fname,self.ftype = QFileDialog.getOpenFileName(self, "Open File", "", 
                                             "Image Files (*.png *.jpg *.bmp);;Text Files (*.txt);;All Files (*)")#如果添加一个内容则需要加两个分号
        # 该方法返回一个tuple,里面有两个内容，第一个是路径， 第二个是要打开文件的类型，所以用两个变量去接受
        # 如果用户主动关闭文件对话框，则返回值为空
        self.imageWindow.setPixmap(QPixmap(self.fname))
        self.imageMessage.setText(self.fname)
        self.imageMessage.setAlignment(Qt.AlignLeft)
        print(self.fname)
        return self.fname , self.ftype
    
    def paintEvent(self,event):   # 用矩形把识别到的文字区域圈起来
        painter = QPainter(self.imageWindow)
        pen = QPen(Qt.red)
        pen.setWidth(2)
        painter.setPen(pen)
        painter.drawRect(int(self.vertex[0]),int(self.vertex[1]),int(self.vertex[2]),int(self.vertex[3]))

    def generateRectOnText(self,x,y,w,h):
        self.vertex = (x,y,w,h)
